package dawnland03.model.team;

import dawnland03.model.quest.QuestFactory;
import dawnland03.model.quest.QuestManager;

import java.util.concurrent.CountDownLatch;
import java.util.Date;
import java.text.SimpleDateFormat;

/**
 * User: Petru Obreja (obrejap@yahoo.com)
 * Date: Feb 13, 2010
 * Time: 10:31:43 PM
 */
public class TeamBrain implements Runnable {
    private final Team team;
    private final CountDownLatch syncronizedStart;
    private final SimpleDateFormat simpleDateFormat;

    public TeamBrain(Team team) {
        this.team = team;
        if (team.getInitialNumberOfTeamMembers() > 0) {
            syncronizedStart = new CountDownLatch(team.getInitialNumberOfTeamMembers());
        } else {
            syncronizedStart = new CountDownLatch(0);
        }
        simpleDateFormat = new SimpleDateFormat("HH:mm:ss-SSS");
    }

    public synchronized void signalTeamMemberIsReady() {
        syncronizedStart.countDown();
    }

    public void run() {
        System.out.println(simpleDateFormat.format(new Date()) + " Team " + team + " starts.");
        try {
            syncronizedStart.await(); //wait for all team members to init
            Thread.sleep(1000);
            QuestManager.getQuestManager().addQuest(QuestFactory.createGatherCoalQuest(1700));
//            QuestManager.getQuestManager().addQuest(QuestFactory.createMoveQuest(22));
//            QuestManager.getQuestManager().addQuest(QuestFactory.createMoveQuest(61));
//            QuestManager.getQuestManager().addQuest(QuestFactory.createMoveQuest(1));
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(simpleDateFormat.format(new Date()) + " Team " + team + " ends.");
    }
}
